"use strict";
const __extends =
  (this && this.__extends) ||
  (function () {
    let extendStatics = function (d, b) {
      extendStatics =
        Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array &&
          function (d, b) {
            d.__proto__ = b;
          }) ||
        function (d, b) {
          for (const p in b)
            if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p];
        };
      return extendStatics(d, b);
    };
    return function (d, b) {
      extendStatics(d, b);
      function __() {
        this.constructor = d;
      }
      d.prototype =
        b === null
          ? Object.create(b)
          : ((__.prototype = b.prototype), new __());
    };
  })();
Object.defineProperty(exports, "__esModule", { value: true });
const React = require("react");
const PropTypes = require("prop-types");

// var ReactDOM =  require('react-dom');
// var AdvanceSearchForm = require("./AdvanceSearchForm");
const swal = require("sweetalert"); //为Advanced Search 引入sweetalert弹窗
let searchThis = null;
const advacneSearchParams = {
  title: "",
  author: "",
  publisher: "",
  category: "",
  provider: "all",
};
// 禁止输入到搜索关键词的特殊字符
// const bandCharts = "@#\$%\^&\*\?"
// const bandCharts = /[@#\$%\^&\*\?]+/g
const bandCharts = /[@#]+/g;

// 检查是否需要特殊约束条件的搜索
function getSearchRange() {
  // in Hidden Books
  // suppressed
  const hiddenBooksParam = "&qRange=hiddenBooks";
  if (window.location.pathname.indexOf("suppressed") != -1) {
    return hiddenBooksParam;
  } else if (window.location.pathname.indexOf("hiddenBooks") != -1) {
    return hiddenBooksParam;
  }
  // else if(getUrlParam('qRange') == 'hiddenBooks'){
  //   return hiddenBooksParam
  // }
  else {
    return null;
  }
}

function getASFormDom() {
  // ReactDOM.render(<AdvanceSearchForm />, wrapper);

  const keyUpAttrs =
    `
        onkeyup="value=value.replace(` +
    bandCharts +
    ` ,'')" 
        onpaste="value=value.replace(` +
    bandCharts +
    ` ,'')" 
        oninput = "value=value.replace(` +
    bandCharts +
    ` ,'')"
    `;
  const AdvanceSearchForm =
    `
        <div class="as-form-body">
        <table>
            <tr class="as-form-row">
                <td><span>Title</span></td>
                <td><input class="ad-input" id="as-input-title" value="` +
    advacneSearchParams["title"] +
    `" name="title" ` +
    keyUpAttrs +
    ` /></td>
            </tr>
            <tr class="as-form-row">
                <td><span>Author</span></td>
                <td><input class="ad-input" id="as-input-author" value="` +
    advacneSearchParams["author"] +
    `" name="author" ` +
    keyUpAttrs +
    ` /></td>
            </tr>
            <tr class="as-form-row">
                <td><span>Publisher</span></td>
                <td><input class="ad-input" id="as-input-publisher" value="` +
    advacneSearchParams["publisher"] +
    `" name="publisher" ` +
    keyUpAttrs +
    ` /></td>
            </tr>
            <tr class="as-form-row">
                <td><span>Category</span></td>
                <td><input class="ad-input" id="as-input-category" value="` +
    advacneSearchParams["category"] +
    `" name="category" ` +
    keyUpAttrs +
    ` /></td>
            </tr>
            <tr class="as-form-row">
                <td><span>Provider</span></td>
                <td><select class="ad-select" id="as-input-category" name="provider" value="` +
    advacneSearchParams["provider"] +
    `" >
                    <option value="all">All</option>
                    <option value="Project Gutenberg">Project Gutenberg</option>
                    <option value="Overdrive">Overdrive</option>
                    <option value="DRM">DRM</option>
                    <option value="Content Server">Content Server</option>
                </select></td>
            </tr>
        </table>
        </div>
    `;
  // var AdvanceSearchForm = `<div>123</div>`
  // var AdvanceSearchForm = '<div class="test">'+testCp+'</div>'

  const wrapper = document.createElement("div");
  wrapper.innerHTML = AdvanceSearchForm;
  // let el = wrapper.firstChild;
  const el = wrapper;
  return el;
}

// 清空查询输入项
function cleanAsForm() {
  // console.log('cleanAsForm')

  const inputsObjects = document.getElementsByClassName("ad-input");
  for (let i = 0; i < inputsObjects.length; i++) {
    inputsObjects[i].value = null;
  }

  const selectObjects = document.getElementsByClassName("ad-select");
  for (let i = 0; i < selectObjects.length; i++) {
    selectObjects[i].value = "all";
  }

  const params = advacneSearchParams;
  Object.keys(params).forEach((key) => {
    if (key == "provider") {
      advacneSearchParams[key] = "all";
    } else {
      advacneSearchParams[key] = "";
    }
  });

  return advacneSearchParams;
}

// 执行AdvanceSearch查询
function doAdvanceSearch(params, _this = searchThis) {
  console.log("开始搜索 Advanced Search");
  // alert(123);
  // 设置查询参数
  // var searchTerms = encodeURIComponent(_this.refs["input"]["value"]);
  // if(!title || title == '') title = '[ALL]'
  // var searchTerms = title

  // console.log("advance search 搜索内容",params)
  let searchTerms;
  if (!params || params === null) {
    // var searchTerms = '[ALL]'
    searchTerms = JSON.stringify({
      provider: "all",
    });
  } else {
    searchTerms = {};
    Object.keys(params).forEach((key) => {
      let val = params[key];
      if (val) val = val.replace(/(^\s*)|(\s*$)/g, ""); //去首尾空格
      if (val && val.length > 50) {
        alert("Each item is limited to 50 characters");
        return;
      }
      if (val && val != "") {
        searchTerms[key] = params[key];
      }
      // else{
      //     searchTerms[key] = '|ALL|'
      // }
    });
    searchTerms = JSON.stringify(searchTerms);
  }
  searchTerms = encodeURIComponent(searchTerms); // URL Encode
  // searchTerms = urlencode(searchTerms) // URL Encode
  // console.log('查询json',searchTerms)

  // 拼接查询api的url
  let _a, _b;
  let url =
    (_a = _this.props.searchData) === null || _a === void 0
      ? void 0
      : _a.template(searchTerms);
  if (_this.props.allLanguageSearch) {
    url += "&language=all";
  }

  const searchRange = getSearchRange();
  if (searchRange) {
    url += searchRange;
  }
  console.log("获取search url", url);

  // 执行查询
  (_b = _this.context.router) === null || _b === void 0
    ? void 0
    : _b.push(_this.context.pathFor(url, null));

  return;
}

//动态
function setAdvacneSearchParamsInput(obj) {
  // console.log('输入值改变 target',obj.target)
  const inputObj = obj.target;
  if (advacneSearchParams[inputObj.name] !== undefined) {
    advacneSearchParams[inputObj.name] = inputObj.value;
  }
  // console.log('查询对象',advacneSearchParams);
}

//增加监听
function addAdInputLisetner() {
  // for(let i=0;i<10000000;i++){}
  // console.log('增加监听')
  const inputsObjects = document.getElementsByClassName("ad-input");
  for (let i = 0; i < inputsObjects.length; i++) {
    inputsObjects[i].addEventListener("input", setAdvacneSearchParamsInput);
  }

  const selectObjects = document.getElementsByClassName("ad-select");
  for (let i = 0; i < selectObjects.length; i++) {
    selectObjects[i].addEventListener("change", setAdvacneSearchParamsInput);
  }

  // ad-select
}

//自定义Advanced Search
function openAdvancedSearchDalog() {
  const _this = searchThis;
  const asFormDom = getASFormDom();
  swal({
    // text: 'Advanced Search',
    // content: "input",
    content: asFormDom,
    buttons: {
      Search: {
        text: "Search",
        value: true,
        className: "adbtn-search",
      },
      Reset: {
        type: "cancel",
        text: "Reset",
        value: "Reset",
        closeModal: false,
        className: "adbtn-reset",
      },
    },
    className: "advanced-search-dalog",
  })
    .then((value) => {
      console.log("swal then value:", value);

      if (value == "Reset") {
        console.log("重置");
        cleanAsForm();
        swal.stopLoading();
        swal.close();
        openAdvancedSearchDalog();
        return;
      } else if (!value) {
        swal.stopLoading();
        return;
      }
      swal.stopLoading();
      doAdvanceSearch(advacneSearchParams, _this);
      return;
    })
    .catch((err) => {
      // console.log('发生错误',err)
      if (err) {
        swal("Oh noes!", "Search failed!" + err, "error");
      } else {
        swal.stopLoading();
        swal.close();
      }
    });
  addAdInputLisetner();
}

function urlencode(str) {
  str = (str + "").toString();
  return encodeURIComponent(str)
    .replace(/!/g, "%21")
    .replace(/'/g, "%27")
    .replace(/\(/g, "%28")
    .replace(/\)/g, "%29")
    .replace(/\*/g, "%2A")
    .replace(/%20/g, "+");
}

/** Search box. */
const Search = /** @class */ (function (_super) {
  __extends(Search, _super);
  function Search(props) {
    const _this = _super.call(this, props) || this;
    _this.onSubmit = _this.onSubmit.bind(_this);
    return _this;
  }

  // 生成打开Advanced Search弹窗的按钮div
  const AdvancedSearchBtnElement = React.createElement(
    "div",
    {
      className: "btn btn btn-default",
      onClick: () => {
        openAdvancedSearchDalog();
      },
      style: {
        borderRadius: "5px",
        border: "1px solid $linkcolor",
        marginTop: "-7px",
        padding: "6px 12px",
        fontWeight: "bold",
        transition: "all 0.2s",
        background: "#1B7FA7",
      },
    },
    "Advanced Search"
  );
  // AdvancedSearchBtnElement.onClick = openAdvancedSearchDalog();

  Search.prototype.render = function () {
    searchThis = this;
    // 生成搜索Html组件
    return React.createElement(
      "div",
      { className: "search", role: "search" },
      this.props.searchData &&
        React.createElement(
          "form",
          {
            onSubmit: this.onSubmit,
            className: this.props.className || "form-inline",
          },
          React.createElement("input", {
            className: "form-control",
            ref: "input",
            "aria-label": "Enter search keyword or keywords",
            type: "text",
            name: "search",
            title: this.props.searchData.shortName,
            placeholder: this.props.searchData.shortName,
            onKeyUp: (e) => {
              // console.log('普通搜索框 onKeyUp',e.target)
              e.target.value = e.target.value.replace(bandCharts, "");
            },
            onPaste: (e) => {
              e.target.value = e.target.value.replace(bandCharts, "");
            },
            onInput: (e) => {
              e.target.value = e.target.value.replace(bandCharts, "");
            },
          }),
          "\u00A0",
          React.createElement(
            "button",
            { className: "btn btn btn-default", type: "submit" },
            "Search"
          ),
          AdvancedSearchBtnElement
        )
    );
  };
  Search.prototype.componentWillMount = function () {
    let _a, _b;
    if (this.props.url) {
      (_b = (_a = this.props).fetchSearchDescription) === null || _b === void 0
        ? void 0
        : _b.call(_a, this.props.url);
    }
  };
  Search.prototype.componentWillUpdate = function (props) {
    if (props.url && props.url !== this.props.url) {
      props.fetchSearchDescription(props.url);
    }
  };
  Search.prototype.onSubmit = function (event) {
    // console.log('开始普通搜索',this)
    let _a, _b;
    let searchTerms = this.refs["input"]["value"].trim();
    // // 增加搜索条件
    // if (!searchTerms || searchTerms.trim() === "") {
    //   alert("搜索内容不能为空格");
    //   return;
    // }
    // console.log("advance search 搜索内容",searchTerms)
    if (!searchTerms || searchTerms === "") {
      searchTerms = JSON.stringify({
        provider: "all",
      });
    } else {
      searchTerms = searchTerms.replace(/(^\s*)|(\s*$)/g, ""); //去首尾空格
    }
    if (searchTerms && searchTerms.length > 50) {
      console.log(searchTerms, searchTerms.length);
      alert("50 characters only");
      return;
    }

    searchTerms = encodeURIComponent(searchTerms); // URL Encode

    let url =
      (_a = this.props.searchData) === null || _a === void 0
        ? void 0
        : _a.template(searchTerms);
    if (this.props.allLanguageSearch) {
      url += "&language=all";
    }

    const searchRange = getSearchRange();
    if (searchRange) {
      url += searchRange;
    }

    (_b = this.context.router) === null || _b === void 0
      ? void 0
      : _b.push(this.context.pathFor(url, null));
    // console.log("普通搜索URL", url);

    event.preventDefault();
  };
  Search.contextTypes = {
    router: PropTypes.object.isRequired,
    pathFor: PropTypes.func.isRequired,
  };
  return Search;
})(React.Component);

exports.default = Search;

// 工具方法
function getUrlParam(name) {
  const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
  const r = window.location.search.substr(1).match(reg); //匹配目标参数
  if (r != null) return unescape(r[2]);
  return null; //返回参数值
}
